package com.woniuxy.util;

import com.woniuxy.common.Result;
import com.woniuxy.common.StatusCode;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.messages.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description 处理文件的工具类
 * @Author Joker
 * @Date 21:48 2021/5/13
 *
 */
@Slf4j
@Component
public class MinioUtil {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.port}")
    private Integer port;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;


    private static MinioClient minioClient;
    /**
     * @Author Joker
     * @Description 初始化MinioClient的方法
     * @Date  
     * @Param []
     * @Return io.minio.MinioClient 返回minioClient对象
     **/
    public MinioClient init() {
        if (minioClient == null) {
            minioClient = MinioClient.builder().endpoint(endpoint, port, false).credentials(accessKey, secretKey).build();
        }
        return minioClient;
    }
    /**
     * @Author Joker
     * @Description 获取所有的MinioClient桶对象
     * @Date  
     * @Param []
     * @Return java.util.List<io.minio.messages.Bucket>
     **/
    public List<Bucket> getAllBucket() throws Exception {
        // 获取minio中所以的bucket
        List<Bucket> buckets = init().listBuckets();
        for (Bucket bucket : buckets) {
            log.info("bucket 名称: {}  bucket 创建时间: {}", bucket.name(), bucket.creationDate());
        }
        return buckets;
    }
    public String getUrlByObjectName(String objectName) {
        String objectUrl = null;
        try {
            objectUrl = init().getObjectUrl(bucketName, objectName);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return objectUrl;
    }


    /**
     * @Author Joker
     * @Description 上传至minio服务器中
     * @Date  
     * @Param [inputStream, fileName]
     * @Return java.lang.String 返回值为存入的链接,为后面的下载做铺垫,并存入表格
     **/
    public Result uploadToMinio(InputStream inputStream, String fileName) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 文件存储的目录结构
            String fileNameSuffix = fileName.substring(fileName.indexOf("."));
            String fileNamePre = UUID.randomUUID().toString().replace("-","");
            String objectName = sdf.format(new Date())+"/"+(fileNamePre+fileNameSuffix);
            // size控制文件大小
            long size = inputStream.available();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, size, -1)
                    .build();
            // 上传到minio
            init().putObject(putObjectArgs);
            String str = endpoint + "/" + bucketName + "/" + objectName;
            log.info("文件上传成功!");
            inputStream.close();
            return new com.woniuxy.common.Result(true, StatusCode.OK, "操作成功",str);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "操作失败");
        }
    }

    /**
     * @Author Joker
     * @Description 根据objectName从minio中下载文件到指定的目录
     * @Date  
     * @Param [objectName, response]
     * @Return void
     **/
    //HttpServletRequest request, HttpServletResponse response
    public void downloadFileFromMinio(String objectName,  String fileName, String dir) throws Exception {
        GetObjectArgs objectArgs = GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        InputStream inputStream = init().getObject(objectArgs);
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream outputStream =  new FileOutputStream(new File(dir, fileName.substring(fileName.lastIndexOf("/")+1)));

        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        log.info("下载成功");
        outputStream.close();
        inputStream.close();
    }

}

